package com.yc.framework.utils;

import cn.gjing.tools.excel.ExcelFactory;
import cn.gjing.tools.excel.read.ExcelReader;
import com.yc.framework.baseClass.BaseEntity;
import com.yc.framework.baseClass.BaseService;
import com.yc.framework.baseClass.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class ExcelUtils {

//    demo:
//    @Autowired
//    ExcelUtils excelUtils;
//
//    @PostMapping("/import")
//    public R importProduct(MultipartFile file) {
//        return excelUtils.importModel(file, service, Product.class);
//    }
//
//    @GetMapping("/export")
//    public void exportProduct(HttpServletResponse resp) {
//        excelUtils.exportModel(Product.class, resp, service.list());
//    }



    @Value("${file.upload.path}")
    private String path;


    /**
     * excel导入数据
     *
     * @param file
     * @param service
     * @param clz
     * @param <T>
     * @return
     */
    public <T extends BaseEntity> R importModel(MultipartFile file, BaseService service, Class<T> clz) {
        String originalFileName = file.getOriginalFilename();//原始文件名
        String name = String.format("%s%s", UUID.randomUUID().toString().toLowerCase(),
                originalFileName.substring(originalFileName.lastIndexOf(".")));
        String path = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String pathName = path + name;
        String realPath = this.path + path;
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File f = new File(realPath, name);
        try {
            file.transferTo(f);//写入文件
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        InputStream input = null;
        try {
            input = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ExcelReader<T> reader = new ExcelReader<>(clz, input);
        List<T> list = reader.read();
        return service.saveModelBatch(list);
    }

    /**
     * 导出excel数据
     * @param cls
     * @param resp
     * @param ps
     * @param <T>
     */
    public <T extends BaseEntity> void exportModel(Class<T> cls,HttpServletResponse resp,List<T> ps)
    {
        ExcelFactory.createWriter(cls,resp,ps).write();
    }
}
